package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.page.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
  @Autowired
  private  CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> pageBrands(String key, Integer page, Integer size) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);  //页数不能超过100
        size = Math.max(size, 5);    //条数不能低于5
        // 2.分页
        Page<Brand> pages = new Page<>(page, size);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(pages);
        // 5.封装结果
        List<Brand> list = pages.getRecords();
        return new PageDTO<>(pages.getTotal(), pages.getPages(), BrandDTO.convertEntityList(list));
    }

    @Override
    public List<BrandDTO> queryBrandByCid(Integer id) {
        BrandMapper baseMapper = getBaseMapper();
        List<Brand> brands = baseMapper.queryBrandByCid(id);
        return BrandDTO.convertEntityList(brands);
    }

    @Override
    @Transactional  //声明式事务
    public void insertBrand(BrandDTO brandDTO) {
        //新增商品的同时还需要更新中间表
        //BrandDTO中包含了对应的分类id信息(Liset)
        Brand brand = brandDTO.toEntity(Brand.class);
        save(brand);  //mybatispius中提供的方法  插入一条记录
        //开始更新中间表  添加新的关系
        // 封装中间表对象的集合
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
        //解析:首先根据brandDTO获取对应的分类id集合
        //     然后转换成steam流(包含遍历)
        //     使用map方法变成map集合(key就是遍历的分类id  值是商品id)
        //      转换成list集合

      /*  //方法2
        Brand brand2 = brandDTO.toEntity(Brand.class);
        save(brand);

        ArrayList<CategoryBrand> categoryBrand = new ArrayList<>();
        for (Long categoryId : brandDTO.getCategoryIds()) {
            categoryBrand.add(CategoryBrand.of(categoryId, brand2.getId()));  //of 是构造器
        }*/

    }

    @Override
    @Transactional
    public void putBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand并回显id
        updateById(brand);
        //先清理之前的关连关系
        //delete from tb_category_brand where brand_id =  #{id}
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        //重建分类和品牌的关系
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());

    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        boolean b = this.categoryBrandService.deleteByBrandId(id);
        if (!b) {
            throw new LyException(500, "删除商品失败");
        }
        boolean b1 = removeById(id);
        if (!b1) {
            throw new LyException(500, "删除商品失败");
        }
    }

    //抽取公共部分
    private void saveCategoryBrand(List<Long> categoryIds, Long id) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(categoryId -> CategoryBrand.of(categoryId, id))
                .collect(Collectors.toList());

        this.categoryBrandService.saveBatch(categoryBrands);
    }

}
